<?php
/**
 * @Author: king
 * @Last Modified by:   king
 * Date: 2018/6/5
 * Time: 16:44
 */
namespace App\Tools;
/**
 * AES 加密 解密类库
 * @by guokunsheng
 * Class Aes
 * @package app\common\lib
 */
class Aes
{
    private $key = null;
    private $iv = null;

    /**
     *
     * @param string $key 密钥
     * @return String
     */
    public function __construct()
    {
        $this->key = config('app.aes_key');
        $this->iv = config('app.aes_iv');
    }

    /**
     * 解密字符串
     * @param string $data 字符串
     * @return string
     */
    public function decryptWithOpenssl($data)
    {
        return openssl_decrypt(base64_decode($data),config('app.aes_method'),$this->key,OPENSSL_RAW_DATA,$this->iv);
    }

    /**
     * 加密字符串
     * @param string $data 字符串
     * @return string
     */
    public function encryptWithOpenssl($data)
    {
//        echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
      //  echo base64_encode(openssl_encrypt("123456","AES-128-CBC","1234567890123456",OPENSSL_RAW_DATA,"1234567890123456"));die;
//        $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, self::$iv);
//        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
        return base64_encode(openssl_encrypt($data,config('app.aes_method'),$this->key,OPENSSL_RAW_DATA,$this->iv));
    }

    function pkcs7_pad($str)
    {
        $len = mb_strlen($str, '8bit');
        $c = 16 - ($len % 16);
        $str .= str_repeat(chr($c), $c);
        return $str;
    }

}